#ifndef _M_POOL_H_
#define _M_POOL_H_

/**
 * 内存池，线程安全，可以用于消息队列
 */

#include <pthread.h>
#include "cqueue.h"

#define MPOOL_DEF_SIZE  10240
template <typename T>
class MPool{
    public:
        MPool(size_t size = MPOOL_DEF_SIZE):m_queue(size){
            assert(pthread_rwlock_init(&m_lock, NULL)==0);
        }

        ~MPool(){
            pthread_rwlock_destroy(&m_lock);
        }

        bool put(T t){
            pthread_rwlock_wrlock(&m_lock);
            bool res = m_queue.push(t);
            pthread_rwlock_unlock(&m_lock);
            return res;
        }

        T* get(){
            pthread_rwlock_rdlock(&m_lock);
            T* t = m_queue.get();
            pthread_rwlock_unlock(&m_lock);
            return t;
        }
        
        T* pop(){
            pthread_rwlock_wrlock(&m_lock);
            T* t = m_queue.pop();
            pthread_rwlock_unlock(&m_lock);
            return t;
        }

        T pop_body(){
            pthread_rwlock_wrlock(&m_lock);
            T* t = m_queue.pop();
            T tt;
            tt.port = 0;
            if(t != NULL){
                tt = *t;
            }
            pthread_rwlock_unlock(&m_lock);
            return tt;
        }

        size_t length(){return m_queue.length();}
        size_t size(){return m_queue.size();}

    private:
        CQueue<T>               m_queue;
        pthread_rwlock_t        m_lock;
};

#endif
